public class TestHeap {
    private int[] elem;
    private int  usedSize;

    public TestHeap(){
        this.elem=new int[10];
    }

    public void initHeap(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i]=array[i];
            usedSize++;
        }
    }
    
    public void createHeap(){
        for (int parent = (usedSize-1-1)/2; parent >=0 ; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    private void shiftDown(int parent, int usedSize) {
        int child=2*parent+1;//左孩子下标

        while (child<usedSize){
            if(child+1<usedSize && elem[child]<elem[child+1]){
                child++;
            }
            if(elem[child]>elem[parent]){
                swap(child,parent);
                parent=child;
                child=2*parent+1;
            }else {
                break;
            }
        }
    }

    private void swap(int a,int b){
        int t=elem[a];
        elem[a]=elem[b];
        elem[b]=t;
    }
}
































